<template>
  <view class="cu-form-group">
    <view class="title"><text v-if="required" class="text-red">*</text>{{title}}</view>
    <picker :disabled="disabled" :range="options" :name="name" :value="pickerValue" range-key="label" @change="onPickerChange">
      <view class="picker">
        {{pickerValue > -1 ? options[pickerValue].label : placeholder}}
      </view>
    </picker>
  </view>
</template>

<script lang="ts" setup>
import {inject, ref, watchEffect,onMounted} from "vue";

interface CuPickerOpt {
  value: string | number
  label: string
}

interface CuPickerProps {
  required?: boolean
  title: string
  name?: string
  options: CuPickerOpt[]
  disabled?: boolean
  placeholder: string
}

const props = withDefaults(defineProps<CuPickerProps>(), {
  required: false,
  mode: 'selector',
  disabled: false,
  placeholder: '请选择'
})

const emit = defineEmits<{
  (e: 'change', value: any): void
}>()

const fields = inject<any>('fields')
const validate = inject<any>('validate')

const pickerValue = ref(-1)

watchEffect((onInvalidate) => {
		if (props.name){
		  pickerValue.value = props.options?.findIndex(item => item.value == fields[props.name as string])
		  if (props.required){
		    validate[props.name] = pickerValue.value >= 0
		  }
		}
})

function onPickerChange(e: any){
  const idx = e.detail.value
  if (idx < 0){
    return
  }
  const value = props.options[idx].value
  if (props.name){
    fields[props.name] = value
  }
  emit('change', value)
}
</script>

<style scoped>

</style>
